package ivansalvadori.diariopushweb.view.termo;

import ivansalvadori.diariopushweb.model.Diario;
import ivansalvadori.diariopushweb.model.Termo;
import ivansalvadori.diariopushweb.model.Usuario;
import ivansalvadori.diariopushweb.service.UsuarioService;
import ivansalvadori.diariopushweb.view.security.MySession;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.markup.html.form.CheckBoxMultipleChoice;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RadioChoice;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

@SuppressWarnings("serial")
public class TermoForm extends Form<Termo> {

	@SpringBean
	private UsuarioService usuarioService;

	private static final List<String> TIPOS = Arrays.asList(new String[] {
			"Nome", "Número de Documento", "Texto Exato" });

	public TermoForm(Termo termo) {
		super("termoForm");
		IModel<Termo> model = new CompoundPropertyModel<Termo>(termo);
		this.setModel(model);

		RequiredTextField<String> campoTermo = new RequiredTextField<String>(
				"termo");
		add(campoTermo);

		add(new RadioChoice<String>("tipo", TIPOS));

		List<Diario> diarios = usuarioService.listarDiarios();

		CheckBoxMultipleChoice<Diario> diarioChoice = new CheckBoxMultipleChoice<Diario>(
				"diarios");
		diarioChoice.setChoices(diarios);
		diarioChoice.setChoiceRenderer(new ChoiceRenderer<Diario>("entidade",
				"codigo"));
		diarioChoice.setOutputMarkupId(true);

		add(diarioChoice);

	}


	@Override
	protected void onValidateModelObjects() {
		// TODO Auto-generated method stub
		super.onValidateModelObjects();

		System.out.println(getModelObject().getDiarios());

		if( getModelObject().getTipo() == null ){
			error("Selecione o tipo do termo.");
		}

		if( getModelObject().getDiarios().size() == 0 ){
			error("Selecione pelo menos um diário.");
		}

	}

	@Override
	public final void onSubmit() {
		Termo termo = getModelObject();
		Usuario usuario = ((MySession) getSession()).getUsuario();
		termo.setUsuario(usuario);
		usuarioService.inserirTermo((this.getModelObject()));
		setResponsePage(GerenciadorTermo.class);
	}

}
